<template>
  <section>
    <page-view>
      <template #option>
        <div class="btn-box">
          <el-button type="primary" @click="onAdd">新增</el-button>
          <el-button :disabled="selection.length == 0" type="primary" @click="onBatchEdit">批量设置</el-button>
        </div>
      </template>
      <template #form>
        <SearchForm :data-form="form" @onReset="onSearch" @on-search="onSearch">
          <el-form-item prop="companyCode">
            <SelectSearch v-model="form.companyCode" :info="COMP_SEARCH_CONF" @on-selectListData=""></SelectSearch>
          </el-form-item>
          <el-form-item prop="orgCode">
            <el-cascader v-model="form.orgCode" :disabled="!form.companyCode" :options="orgData" :props="cascaderProps"
                         clearable
                         placeholder="请选择部门" style="width:100%"/>
          </el-form-item>
          <el-form-item prop="budgetCostCenterCode">
            <el-input v-model="form.budgetCostCenterCode" clearable placeholder="请输入默认预算成本中心编码"/>
          </el-form-item>
          <el-form-item prop="checkCostCenterCode">
            <el-input v-model="form.checkCostCenterCode" clearable placeholder="请输入默认核算成本中心编码"/>
          </el-form-item>
        </SearchForm>
      </template>
      <template #table="tableScope">
        <PubilcTable @on-selectChange="selectChange" show-select  :isSlot="false" :list-config="TABLE_DATA_CONF" :page-data="pageData" :showIndex="false"
                     :table-data="tableData" :tableHeight="tableScope.tableHeight" :translateTextDeal="translateTextDeal"
                     @on-action="onAction"/>
      </template>
    </page-view>
    <AddOrEdit v-if="dialogVisible" :dataForm="dataForm" :dialogVisible="dialogVisible" :type="type"
               @on-close="onDialClose" @on-update="onSearch"></AddOrEdit>
    <BatchUpdateDialog v-if="batchVisible" :select-list="selection" @on-close="batchVisible = false" @on-update="onSearch"/>
  </section>
</template>

<script name="depCostCenterConfig">
import {TABLE_DATA_CONF, COMP_SEARCH_CONF, } from './config'
import {onMounted, watch, reactive, toRefs} from 'vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import api from '@/api'
import SelectSearch from '@/components/SelectSearch/index.vue'
import AddOrEdit from "@/views/depCostCenterConfig/components/AddOrEdit.vue";
import BatchUpdateDialog from './components/BatchUpdateDialog.vue'

export default {
  components: {
    AddOrEdit,
    SelectSearch,
    BatchUpdateDialog
  },
  setup() {
    const state = reactive({
      form: {
        companyCode: '',
        orgCode: '',
        budgetCostCenterCode: '',
        checkCostCenterCode: ''
      },
      COMP_SEARCH_CONF,
      TABLE_DATA_CONF,
      cascaderProps: {
        checkStrictly: true,
        label: 'label',
        value: 'value',
        emitPath: false,
        lazy: true,
        lazyLoad(node, resolve) {
          let params = {parentId: node.value || state.form.companyCode}
          methods.loadDepartment(params).then(res => {
            resolve(res)
          })
        }
      },
      orgData: [],
      pageData: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      dialogVisible: false,
      type: '',
      dataForm: {},
      selection: [],
      batchVisible: false
    })

    const methods = {
      // 获取列表数据
      getList() {
        const params = {
          ...state.pageData,
          ...state.form
        }
        api.costCenter.depListData(params).then(res => {
          state.pageData.total = res.total
          state.tableData = res.list
        })
      },

      // 异步获取部门树
      loadDepartment(params) {
        return new Promise(resolve => {
          api.user.getDepartmentTree(params).then(res => {
            resolve(res)
          })
        })
      }
    }

    const handler = {
      translateTextDeal(item, val, row) {
        if (!val) {
          return ''
        }

        if (item.alias === 'budgetCostCenterName') {
          return val + '[' + row['budgetCostCenterCode'] + ']'
        }

        if (item.alias === 'checkCostCenterName') {
          return val + '[' + row['checkCostCenterCode'] + ']'
        }

        if (item.alias === 'outerBudgetCostCenters') {
          return val.map(item => `${item.outerBudgetCostCenterName}[${item.outerBudgetCostCenterCode}]`).join(',')
        }
      },
      // 搜索
      onSearch() {
        state.pageData.pageNum = 1
        methods.getList()
      },
      // 新增
      onAdd() {
        state.type = 'add'
        state.dialogVisible = true
      },
      // 编辑
      onEdit(row) {
        state.dataForm = {...row}
        state.type = 'edit'
        state.dialogVisible = true
      },
      onDialClose() {
        state.dataForm = {}
        state.dialogVisible = false
      },
      // 删除
      onDel(row) {
        ElMessageBox.confirm(
          '您确定要进行删除操作吗?',
          '温馨提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            api.costCenter.depRemoveCostCenter(row.id).then(res => {
              handler.onSearch()
              ElMessage.success('操作成功')
            })
          })
      },
      // 列表操作
      onAction([item, row]) {
        const obj = {
          'pageNum': methods.getList,
          'pageSize': handler.onSearch,
          'edit': handler.onEdit,
          'del': handler.onDel,
        }
        if (typeof item === 'string') {
          state.pageData[item] = row
          obj[item]()
        } else {
          obj[item.alias](row)
        }
      },
      onBatchEdit() {
        if(state.selection.length == 0) {
          return ElMessage.warning('请选择数据')
        }
        if (new Set(state.selection.map(item => item.companyCode)).size > 1) {
          return ElMessage.warning('请选择同一公司的数据')
        }

        state.batchVisible = true

      },
      selectChange(list) {
        state.selection = list
      }
    }

    watch(
      () => state.form.companyCode,
      (val, preVal) => {
        state.orgData = []
      }
    )

    onMounted(() => {
      handler.onSearch()
    })

    return {
      ...toRefs(state),
      ...handler
    }
  }
}
</script>

<style scoped>

</style>
